package org.opengauss.sqltranslator.dialect.mysql.util;

import org.opengauss.sqltranslator.ExecuteTranslate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class EnumUtils {
    private static final Logger logger = LoggerFactory.getLogger(EnumUtils.class);
    // 泛型方法：根据字段名称获取所有枚举实例中该字段的值
    public static <T> List<T> getFieldValues(Class<? extends Enum<?>> enumClass, String fieldName, Class<T> fieldType) {
        List<T> values = new ArrayList<>();
        // 获取枚举类的所有实例
        Enum<?>[] enumConstants = enumClass.getEnumConstants();
        try {
            // 获取指定字段
            Field field = enumClass.getDeclaredField(fieldName);
            field.setAccessible(true);  // 设置字段可访问
            // 确保字段类型与要求的类型一致
            if (!field.getType().equals(fieldType)) {
                throw new IllegalArgumentException("Field type mismatch.");
            }
            // 遍历枚举实例，获取字段值
            for (Enum<?> enumConstant : enumConstants) {
                @SuppressWarnings("unchecked")
                T value = (T) field.get(enumConstant);  // 获取字段值并转换为目标类型
                values.add(value);
            }
        } catch (NoSuchFieldException | IllegalAccessException e) {
            logger.error(e.getLocalizedMessage());
            throw new RuntimeException(e);
        }
        return values;
    }
}

